#include "TagManager.h"
#include "Environment.h"
#include <iostream>
#include <vector>
#include <dirent.h>
#include <string.h>

namespace phnq
{
	namespace phnqlets
	{
		void scan(map<string,Tag*> &tags, const char *parent, const char *name, char *typeNS=NULL)
		{
			char path[256];
			char ns[256];

			sprintf(path, "%s/%s", parent, name);
		
			DIR *dir = opendir(path);
			if(dir)
			{
				if(typeNS)
					sprintf(ns, "%s%s.", typeNS, name);
				else
					ns[0] = 0;

				struct dirent *pent;
				while(pent = readdir(dir))
				{
					if(strcmp(pent->d_name, ".") && strcmp(pent->d_name, ".."))
						scan(tags, path, pent->d_name, ns);
				}
				closedir(dir);
			}
			else // path represents a file
			{
				int len = strlen(name);
				if(name[len-3] == '.' && name[len-2] == 'j' && name[len-1] == 's')
				{
					char type[128];
					sprintf(type, "%s%s", typeNS, name);
					len = strlen(type);
					type[len-3] = 0;
				
					if(!tags[type])
						tags[type] = new Tag(type, path);
				}
			}
		}
	
		TagManager::TagManager()
		{
			vector<string> resPaths = Environment::getInstance()->getResourcePaths();
			for(int i=0; i<resPaths.size(); i++)
			{
				string s = resPaths[i];
				scan(tags, s.c_str(), "tags");
			}
		}

		TagManager* TagManager::getInstance()
		{
			static TagManager instance;
		
			return &instance;
		}
	
		Tag* TagManager::get(string type)
		{
			return tags[type];
		}
	}
}
